package com.loong.shop.business;

import com.loong.common.executor.AsyncExecutor;
import com.loong.common.mybatis.business.AbstractBusiness;
import com.loong.common.rabbitmq.dto.base.RepositoryEventDto;
import com.loong.shop.common.backend.param.GoodsSizeNameQueryParam;
import com.loong.shop.common.backend.param.GoodsSpecificationReportParam;
import com.loong.shop.common.forehead.param.GoodsSizeNameQueryForeheadParam;
import com.loong.shop.model.GoodsSpecificationName;
import com.loong.shop.mq.GoodsSpecificationReport;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description:
 * @Author: 刘群
 * @Date: 2020/10/27 7:48
 */
@Repository
@Slf4j
public class GoodsSpecificationNameBusiness extends AbstractBusiness<GoodsSpecificationName> {

    @Resource
    private GoodsSpecificationReport goodsSpecificationReport;

    @Resource
    private AsyncExecutor asyncExecutor;

    /**
     * 根据参数查询商品名称
     *
     * @param param 查询参数：店铺id、规格名称
     * @return 商品规格名称集合
     */
    public List<GoodsSpecificationName> findSpecificationNameByParam(GoodsSizeNameQueryForeheadParam param) {
        Condition condition = new Condition(GoodsSpecificationName.class);
        Example.Criteria criteria = condition.createCriteria();
        if (ObjectUtils.isNotEmpty(param.getShopId())) {
            criteria.andEqualTo("shopId", param.getShopId());
        }
        if (ObjectUtils.isNotEmpty(param.getName())) {
            criteria.andLike("name", "%" + param.getName() + "%");
        }
        return findByCondition(condition);
    }

    /**
     * 根据参数查询是否存在重复的规格名称
     *
     * @param param 查询参数：店铺id、规格名称
     * @return 商品规格名称集合
     */
    public List<GoodsSpecificationName> findDuplicationNamesByParam(GoodsSizeNameQueryParam param) {
        Condition condition = new Condition(GoodsSpecificationName.class);
        Example.Criteria criteria = condition.createCriteria();
        //根据规格名称和店铺id查询商品规格名称
        criteria.andEqualTo("name", param.getName());
        criteria.andEqualTo("shopId", param.getShopId());
        return this.findByCondition(condition);
    }

    @Override
    public void updateByPrimaryKeySelective(GoodsSpecificationName model) {
        super.updateByPrimaryKeySelective(model);
        if(ObjectUtils.isNotEmpty(model.getName())){
            asyncExecutor.async(()->{
                    GoodsSpecificationReportParam param = GoodsSpecificationReportParam.builder().goodsSpecificationId(model.getId()).goodsSpecificationNewName(model.getName()).build();
                    goodsSpecificationReport.report(RepositoryEventDto.buildWithUpdate(param));
            });
        }
    }
}
